//plugins/axios.ts
import axios from "axios";
import { ElMessage } from "element-plus";
import router from "../router/index.ts";
import { useTokenStore } from "../stores/token.ts";

const baseURL = "/api";
const axiosInstance = axios.create({ baseURL });

//添加请求拦截器
axiosInstance.interceptors.request.use(
  (config) => {
    //config是请求的配置对象
    //如果有token,则添加到请求头中
    const tokenStore=useTokenStore() //位置一定要放在这里 放在外面就会造成在Vue 实例化或应用挂载前尝试访问 store
    if (tokenStore.token) {
      config.headers["Authorization"] = tokenStore.token;
    }
    return config;
  },

  (error) => {
    return Promise.reject(error);
  }
);

//添加响应拦截器
axiosInstance.interceptors.response.use(
  (response:any) => {
    //判断响应头中是否有token
    const token = response.headers.authorization;
    if(token&& token!=''){ 
      //将token保存到本地
      useTokenStore().setToken(token);
    }
    return response;
  },

   (error:any) => {
     return Promise.reject(error);
  } 
);
export default axiosInstance;
